rest = require("rest")
Config = require("../config")


exports.gGetAccessToken = (code)->

    gGetToken = (code)->
        url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Config.appId + "&secret=" + Config.secret + "&code=" + code + "&grant_type=authorization_code"
        data = yield rest(url,)
        data = JSON.parse(data.entity)
        startTime = Date.now()
        global.weixin ?= {}
        global.weixin.accessToken =
            value: data.access_token
            refreshToken:data.refresh_token
            openid:data.openid
            unionid:data.unionid
            startTime: startTime
        console.log("access token:" + global.weixin.accessToken.value)
        global.weixin.accessToken

    if global.weixin?.accessToken
        startTime = global.weixin.startTime
        currentTime = Date.now()
        time = currentTime - startTime
        if (time > 1.5 * 60 * 60) # 1.5小时后过期
            yield from gGetToken(code)
        else
            console.log("stored access token" + global.weixin.accessToken.value)
            yield global.weixin.accessToken
    else
        yield from gGetToken(code)

